//
//  Weishi_shezhi_vc.m
//  ainkjj
//
//  Created by MAX on 2020/10/21.
//  Copyright © 2020 zhiyiLiu. All rights reserved.
//

#import "Feng_zidong_vc.h"
#import "WSDatePickerView.h"

@interface Feng_zidong_vc ()
<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate,lzyupdatecmd>
@property (nonatomic, strong)NSMutableArray *dataArr;
@property (nonatomic, strong)UITextField *weishiliang_tf;
@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)UITextField *kaishi_tf;
@property (nonatomic, strong)UITextField *jiesu_tf;
@end

@implementation Feng_zidong_vc
- (void)guanbi{
    NSMutableDictionary  *dict = [NSMutableDictionary dictionary];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"Authorization"];
    
    [dict setObject:app_code forKey:@"app_code"];
    [dict setObject:self.device_id forKey:@"device_id"];
    
    [dict setObject:@"set_venting" forKey:@"type"];
    [dict setObject:@"" forKey:@"value"];
    [dict setObject:@"1" forKey:@"is_auto"];
    [PPHTTPRequest req:@"api/pets/App/setDeviceConfig" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            
            if (self.delegate) {
                NSMutableArray *muarr = nil;
                for (NSInteger i = 0; i< 4; i++ ) {
                    [muarr addObject:@{@"reg": @"feed_time",@"value": [NSString stringWithFormat:@"%ld/",i]}];
                }
                
                [self.delegate queryWith_cmd:@"dev" data:muarr];
                
                self.delegate = nil;
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
        
        else
            //            if ([error_code isEqualToString:@""])
        {
            
            [MBProgressHUD showTipMessageInView:response[@"error_msg"]];
            
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showTipMessageInView:[error localizedDescription]];
        
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"自动喂食设置";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭自动" style:UIBarButtonItemStylePlain target:self action:@selector(guanbi)];
    
    
    UIView *v = UIView.new;
    [self.view addSubview:v];
    v.frame = CGRectMake(0, Lzy_StatusBarAndNavigationBarHeight, ScreenWidth, 10);
    v.backgroundColor = UIColor.groupTableViewBackgroundColor;
    
    UILabel *weishiliang_lb = [[UILabel alloc ] initWithFrame:CGRectMake(10, CGRectGetMaxY(v.frame) + 20, 100, 20)];
    [self.view addSubview:weishiliang_lb];
    weishiliang_lb.text = @"喂食量（g）";
    
    UITextField *weishiliang_tf = [[UITextField alloc] initWithFrame:CGRectMake( CGRectGetMaxX(weishiliang_lb.frame), CGRectGetMinY(weishiliang_lb.frame), ScreenWidth - CGRectGetMaxX(weishiliang_lb.frame) - 20, 44)];
    [self.view addSubview:weishiliang_tf];
    self.weishiliang_tf = weishiliang_tf;
    weishiliang_tf.placeholder = @"请输入喂食量";
    weishiliang_tf.center = CGPointMake(weishiliang_tf.center.x, weishiliang_lb.center.y);
    weishiliang_tf.text = @(self.config.num).stringValue;
    [weishiliang_tf setTextAlignment:NSTextAlignmentRight];
    [weishiliang_tf setKeyboardType:UIKeyboardTypeNumberPad];
    
    UIView *sepv1 = UIView.new;
    [self.view addSubview:sepv1];
    sepv1.backgroundColor = UIColor.groupTableViewBackgroundColor;
    sepv1.frame = CGRectMake(0, CGRectGetMaxY(weishiliang_tf.frame) + 10, ScreenWidth, 1);
    
    

    UITextField *kaishi_tf = [[UITextField alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(sepv1.frame) + 10, (ScreenWidth - 60) * 0.5, 44)];
    [self.view addSubview:kaishi_tf];
    [kaishi_tf setBorderStyle:UITextBorderStyleRoundedRect];
    kaishi_tf.placeholder = @"设置起始时分";
    self.kaishi_tf = kaishi_tf;
    kaishi_tf.delegate = self;
    
    UITextField *jiesu_tf = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(kaishi_tf.frame), CGRectGetMinY(kaishi_tf.frame), CGRectGetWidth(kaishi_tf.frame), CGRectGetHeight(kaishi_tf.frame))];
    [self.view addSubview:jiesu_tf];
    jiesu_tf.placeholder = @"设置结束时分";
    [jiesu_tf setBorderStyle:UITextBorderStyleRoundedRect];
    self.jiesu_tf = jiesu_tf;
    jiesu_tf.delegate = self;
    
    UIButton *addbtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth - 50, CGRectGetMinY(sepv1.frame)+10 , 50, 44)];
    [self.view addSubview:addbtn];
    [addbtn setImage:UIImageMake(@"add_icon") forState:UIControlStateNormal];
    [addbtn addTarget:self action:@selector(add_shiduan_action) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.dataArr = self.config.value.mutableCopy;
    
    UITableView *tableView = [[UITableView alloc] init];
    tableView.frame = CGRectMake(0, CGRectGetMaxY(addbtn.frame)+20, ScreenWidth, 4 * 44 + 30);
    self.tableView = tableView;
    [self.view addSubview:tableView];
    tableView.rowHeight = 44;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    self.tableView.editing = YES;
    
    UITextView *jieshaotextview = UITextView.new;
    [self.view addSubview:jieshaotextview];
    jieshaotextview.editable = NO;
    jieshaotextview.frame = CGRectMake(10, CGRectGetMaxY(tableView.frame), ScreenWidth - 2 *10, 80);
    jieshaotextview.text = @"幼猫每天大概需要喂3-4次，每次约10g-15g；成年猫一天1-2次即可，每次约30-50g";
    
    /*
     单次喂水 30s ；全天小于4个时段喂水；全天不间断循环喂水
     喂食 单次1格
     通风
     消毒 单次默认 15分钟
     
     */
    self.weishiliang_tf.text = @"30";
//    [self.weishiliang_tf becomeFirstResponder];

    UIButton *chufabtn = [[UIButton alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(jieshaotextview.frame) + 10, ScreenWidth - 40, 44)];
    [self.view addSubview:chufabtn];
    [chufabtn setTitle:@"保持自动" forState:UIControlStateNormal];
    [chufabtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    chufabtn.layer.cornerRadius = 22;
    chufabtn.layer.masksToBounds = YES;
    [chufabtn setBackgroundColor:appMainColor];
    [chufabtn addTarget:self action:@selector(baocun) forControlEvents:UIControlEventTouchUpInside];
}
- (void)baocun{
   
    
    NSMutableDictionary  *dict = [NSMutableDictionary dictionary];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"Authorization"];
    
    [dict setObject:app_code forKey:@"app_code"];
    [dict setObject:self.device_id forKey:@"device_id"];
    
    [dict setObject:@"set_venting" forKey:@"type"];
    if (self.weishiliang_tf.text.length>0) {
        [dict setObject:self.weishiliang_tf.text forKey:@"num"];
    }else{
        [QMUITips showError:@"请输入喂食量"];
        return;
    }
    
    if (self.dataArr.count == 0) {
        [QMUITips showError:@"设置时段才能开启自动"];
        return;
    }
    
    [dict setObject:[self.dataArr mj_JSONString] forKey:@"value"];
    [dict setObject:@"2" forKey:@"is_auto"];
    [PPHTTPRequest req:@"api/pets/App/setDeviceConfig" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            [QMUITips showSucceed:@"更新成功"];
            if (self.delegate) {
                NSMutableArray *muarr = NSMutableArray.new;
                [muarr addObject:@{@"reg": @"feed_amount", @"value" : self.weishiliang_tf.text}];
                for (NSInteger i = 0; i< self.dataArr.count; i++ ) {
                    NSString *s = self.dataArr[i];
                    NSArray *sarr = [s componentsSeparatedByString:@"/"];
                    NSString *str = [NSString stringWithFormat:@"%ld/2020-07-15 %@:00/2020-07-15 %@:00", i,sarr.firstObject, sarr.lastObject];
                    [muarr addObject:@{@"reg": @"feed_time",@"value": str}];
                }
            
                [self.delegate queryWith_cmd:@"dev" data:muarr];
                
                self.delegate = nil;
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
        
        else
            //            if ([error_code isEqualToString:@""])
        {
            
            [MBProgressHUD showTipMessageInView:response[@"error_msg"]];
            
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showTipMessageInView:[error localizedDescription]];
        
    }];
}
- (void)add_shiduan_action{
    // 判断是否已经四个时间了，可以添加则
    // 弹出开始、结束时间弹窗
    // 选择完毕，判断是否与以前的时间存在重叠，不重叠则 暂时不做太难完成
    // 发送指令
    // 修改UI
    if (self.dataArr.count == 4) {
        return;
    }

    NSString *shijiaduan = [NSString stringWithFormat:@"%@/%@",self.kaishi_tf.text,self.jiesu_tf.text];
    [self.dataArr addObject:shijiaduan];
    [self.tableView reloadData];
}
- (NSMutableArray *)dataArr{
    if(_dataArr == nil)
    {
        _dataArr = [[NSMutableArray alloc] init];
        _dataArr = @[@"07:00/07:30", @"11:00/11:30", @"15:00/15:30", @"20:00/20:30"].mutableCopy;
    }
    
    return _dataArr;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if ([textField isEqual:self.kaishi_tf] || [textField isEqual:self.jiesu_tf]) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.view endEditing:YES];
            
            //时-分
            WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowHourMinute CompleteBlock:^(NSDate *selectDate) {
                
                NSString *dateString = [selectDate stringWithFormat:@"HH:mm"];
                NSLog(@"选择的日期：%@",dateString);
                textField.text = dateString;
            }];
            //        datepicker.dateLabelColor = randomColor;//年-月-日-时-分 颜色
            //        datepicker.datePickerColor = randomColor;//滚轮日期颜色
            //        datepicker.doneButtonColor = randomColor;//确定按钮的颜色
            datepicker.yearLabelColor = [UIColor cyanColor];//大号年份字体颜色
            datepicker.hideBackgroundYearLabel = YES;
            [datepicker show];
        });
    }
    
    
    return YES;
}
#pragma mark - ================== table view data source delegate ==================
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
    }
    cell.textLabel.text = self.dataArr[indexPath.row];
    cell.textLabel.adjustsFontSizeToFitWidth = YES;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return @"设置最多4个时段";
}
// 当table view要删除一行时，会发送此消息到其delegate，这个方法是在UITableVieaDataSource protocol中定义的
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    // 当是要执行删除时
    if(editingStyle == UITableViewCellEditingStyleDelete){

        // 删除cell对应的item
        [self.dataArr removeObjectAtIndex:indexPath.row];
        
            
        // table view 删除行
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
    }
}
@end
